package com.gigi.searchcenterbackendmaster.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gigi.searchcenterbackendmaster.mapper.UserMapper;
import com.gigi.searchcenterbackendmaster.model.dto.UserEsDTO;
import com.gigi.searchcenterbackendmaster.model.entity.UserEntity;
import com.gigi.searchcenterbackendmaster.model.vo.UserVO;
import com.gigi.searchcenterbackendmaster.service.UserService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Gigi
 * @since 2024-08-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public List<UserVO> searchFromEs(String keyword) {
        // 1、构造查询条件

        // 按关键词检索
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StrUtil.isNotBlank(keyword)) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("userName", keyword));
            boolQueryBuilder.should(QueryBuilders.matchQuery("intro", keyword));
            boolQueryBuilder.minimumShouldMatch(1);
        }

        // 过滤出未删除的
        boolQueryBuilder.filter(QueryBuilders.termQuery("ifDelete", 0));

        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder()
                .field("userName")
                .field("intro")
                .preTags("<span style=\"color: red\">")
                .postTags("</span>");

        // 按分数降序排序
        SortBuilder<?> sortByScore = SortBuilders.scoreSort();

        // 组合查询条件
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withSorts(sortByScore)
                .withHighlightBuilder(highlightBuilder)
                .build();

        // 2、调用 ElasticsearchRestTemplate 进行查询
        SearchHits<UserEsDTO> searchHits = elasticsearchRestTemplate.search(searchQuery, UserEsDTO.class);

        //（3、如果需要其他动态字段，根据 id 反查 mysql）

        // 4、封装成 Page 对象返回
        if (!searchHits.hasSearchHits()) {
            return Collections.emptyList();
        }
        return searchHits.getSearchHits().stream().map(item -> {
            UserVO userVO = new UserVO();
            List<String> highlightUserName = item.getHighlightField("userName");
            List<String> highlightIntro = item.getHighlightField("intro");
            userVO.setUserName(CollUtil.isNotEmpty(highlightUserName) ? highlightUserName.get(0) : item.getContent().getUserName());
            userVO.setIntro(CollUtil.isNotEmpty(highlightIntro) ? highlightIntro.get(0) : item.getContent().getIntro());
            userVO.setAvatarUrl(item.getContent().getAvatarUrl());
            return userVO;
        }).collect(Collectors.toList());
    }

}
